from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from heetun.models import Log
from heetun.models import User
from heetun.models import User_Friend_relation
from heetun.forms import AddLogForm
from django.core import serializers
from django.utils import simplejson
from django.http import HttpResponse
from django.db.models import Q


def home(request):
    return render_to_response('heetun/home.html',{ 'Log_list': Log.objects.all() })

def people(request,username):
    para={}
    isFriend = False
    isExists = False
    isSelf = False
    form = AddLogForm()
    try:
        if username== request.user.username:
            isSelf = True
        User.objects.get(username=username)
        isExists = True
        try:
            if request.user.is_authenticated():
                User_Friend_relation.objects.get(user=request.user,friend = User.objects.get(username=username))
                isFriend = True
        except User_Friend_relation.DoesNotExist:
            isFriend = False
        if request.method == 'POST':
            form = AddLogForm(request.POST)
            if form.is_valid():
                # Process form data
                message = form.cleaned_data.get('log', '')
                log = Log()
                log.author = request.user
                log.content = message
                log.save(log)
                form = AddLogForm()
        else:
            action = request.GET.get('action', '')
            friendName = request.GET.get('friend', '')
            if action=='addFriend' and request.user.is_authenticated():
                AddFriendRelation(request,friendName)
                if request.is_ajax():
                    data = CreateJsonSimpleResult(action,'successful')
                    return HttpResponse(data,'application/javascript')
                else:
                    return HttpResponseRedirect("/people/"+username)
            elif action=='removeFriend' and request.user.is_authenticated():
                RemoveFriendRelation(request,friendName)
                if request.is_ajax():
                    data = CreateJsonSimpleResult(action,'successful')
                    return HttpResponse(data,'application/javascript')
                else:
                    return HttpResponseRedirect("/people/"+friendName)
            form = AddLogForm()
    except User.DoesNotExist:
        isExists = False
    
    
    
    para['form']=form
    para['username']=username
    if isSelf:
        # get all friends' name
        arrFriends = GetArrFriendsName(request)
        # get log from current user and say to current user and all the logs from his friends
        para['Log_list']=Log.objects.filter(Q(author__username=username)|Q(audiences__username=username) |Q(author__username__in=arrFriends))[:10]
    else:
        para['Log_list']=Log.objects.filter(Q(author__username=username))[:10]
    para['isAuthenticated']=request.user.is_authenticated()
    para['isFriend']=isFriend
    para['isExists']=isExists
    para['isSelf']=isSelf
    return render_to_response('heetun/people.html',
                              {'para':para})

def RemoveFriendRelation(request,friendName):
    try:
        friend =User.objects.get(username=friendName)
        User_Friend_relation.objects.filter(user=request.user,friend = friend).delete()
    except User.DoesNotExist:
        pass

def AddFriendRelation(request,friendName):
    try:
        friend = User.objects.get(username=friendName)
        User_Friend_relation.objects.get_or_create(user=request.user,friend = friend)
    except User.DoesNotExist:
        pass
        
def CreateJsonSimpleResult(action,result):
    data = {'action':action,'result':result}
    return simplejson.dumps(data)

def GetArrFriendsName(request):
    arrFriendsName = []
    try:
        if request.user.is_authenticated():
            relations = User_Friend_relation.objects.filter(user=request.user)
            for relation in relations:
                arrFriendsName.append(relation.friend.username.strip())
    except User_Friend_relation.DoesNotExist:
        isFriend = False
    return arrFriendsName
    